<template>
  <div class="list">
    <el-form ref="form" v-loading="formLoading" :model="form" label-width="120px" :rules="rules">
      <el-form-item label="公告标题：" class="title" prop="title">
        <el-input v-model.trim="form.title" type="text" :disabled="loading" />
      </el-form-item>
      <el-form-item label="公告内容：" class="content" prop="content">
        <my-editor
          place-holder="请输入内容"
          :value.sync="form.content"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small" :loading="loading" @click="save">保存</el-button>
        <el-button size="small" :disabled="loading" @click="cancle">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import MyEditor from '@/components/MyEditor'
import { announcementAdd, announcementEdit, announcementById } from '@/api'
export default {
  name: 'AnnouncementEdit',
  components: {
    MyEditor
  },
  data() {
    const checkContent = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入内容'))
      }

      try {
        // 2. 创建 DOM 解析器
        const parser = new DOMParser()
        // 3. 将 HTML 字符串转换为 DOM 文档
        const htmlDoc = parser.parseFromString(value, 'text/html')
        // 4. 提取所有文本内容
        const textContent = htmlDoc.body.textContent || ''
        // 5. 去除所有空白字符
        const strippedText = textContent.replace(/\s+/g, '')

        // 6. 检查处理后的文本是否为空
        if (strippedText === '') {
          return callback(new Error('内容不能为空'))
        }

        // 7. 验证通过
        callback()
      } catch (error) {
        console.error('富文本验证异常:', error)
        callback(new Error('富文本内容验证失败，请检查格式'))
      }
    }
    return {
      rules: {
        title: [
          {
            required: true,
            message: '请输入公告标题',
            trigger: 'blur'
          }
        ],
        content: [
          {
            required: true,
            validator: checkContent,
            trigger: 'blur'
          }
        ]
      },
      form: {
        title: '',
        content: ''
      },
      id: '',
      loading: false,
      formLoading: false
    }
  },
  created() {
    this.init()
  },
  methods: {
    init() {
      if (this.$route.query.id) {
        this.id = this.$route.query.id
        this.deteils()
      }
    },
    save() {
      this.$refs.form.validate(async(valid) => {
        if (valid) {
          this.loading = true
          const res = this.id ? await this.editContent() : await this.addContent()
          if (res.code === 0) {
            const text = this.id ? '修改' : '添加'
            this.$message.success(`${text}公告成功`)
            this.cancle()
          }
          this.loading = false
        } else {
          return false
        }
      })
    },
    async addContent() {
      return await announcementAdd(this.form)
    },
    async editContent() {
      const params = {
        ...this.form,
        id: this.id
      }
      return await announcementEdit(params)
    },
    async deteils() {
      if (this.formLoading) return
      this.formLoading = true
      await announcementById({ id: this.id }).then(res => {
        if (res.code === 0) {
          this.form = res.data
        }
      })
      this.formLoading = false
    },
    cancle() {
      this.$router.push('/announcement/list')
    }
  }
}
</script>

<style lang="scss" scoped>
.title{
  width: 500px;
}
.content{
  width: 750px;
}
</style>
